﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace Mystery.SharePoint.WebControls
{
    /// <summary>
    /// Handles redirect to the metadata page
    /// </summary>
    class MetadataRedirect : WebControl
    {
        protected override void OnLoad(EventArgs e)
        {
            if (this.Page.IsPostBack == false)
            {
                if (PerformRedirect() == true)
                {
                    try
                    {
                        if (SPContext.Current.Web.AssociatedOwnerGroup.ContainsCurrentUser == true)
                        {
                            SPUtility.Redirect(UrlPaths.SiteMetadata,
                                SPRedirectFlags.RelativeToLayoutsPage, HttpContext.Current, "First=1");
                        }
                        else
                        {
                            SPUtility.Redirect("error.aspx",
                                SPRedirectFlags.RelativeToLayoutsPage,
                                HttpContext.Current,
                                "ErrorText=" + Resources.PostProvisioning_NotComplete);
                        }
                    }
                    catch (System.Threading.ThreadAbortException)
                    {
                    }
                }
            }
            base.OnLoad(e);
        }

        private bool PerformRedirect()
        {
            string path = base.Page.Request.Url.AbsolutePath;

            StringComparison comp = StringComparison.InvariantCultureIgnoreCase;

            // some pages we don't redirect from
            if (path.EndsWith(UrlPaths.SiteMetadata, comp) == true) return false;
            if (path.EndsWith("_layouts/settings.aspx", comp) == true) return false;
            if (path.EndsWith("_layouts/error.aspx", comp) == true) return false;
            if (path.EndsWith("_layouts/deleteweb.aspx", comp) == true) return false;

            return true;
        }
    }
}
